package vl07.network;

import java.awt.BorderLayout;
import java.awt.Container;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class Browser0 extends JFrame {
	private JLabel lblIP = new JLabel("IP");
	private JTextField txtIP = new JTextField();
	private JLabel lblPort = new JLabel("Port");
	private JTextField txtPort = new JTextField();
	private JButton btnGo;
	private JScrollPane paneInhalt;
	private JTextArea txtInhalt;

	public static void main(String[] args) {
		new Browser0();
	}

	/** Creates new form Browser1 */
	public Browser0() {
		super("Browser 0");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout());

		Box topBox = Box.createHorizontalBox();
		this.add(topBox, BorderLayout.NORTH);

		topBox.add(lblIP);

		txtIP.setText("127.0.0.1");
		txtIP.setPreferredSize(new java.awt.Dimension(200, 21));
		topBox.add(txtIP);

		topBox.add(Box.createHorizontalStrut(30));

		topBox.add(lblPort);

		txtPort.setText("8080");
		txtPort.setPreferredSize(new java.awt.Dimension(50, 21));
		topBox.add(txtPort);

		topBox.add(Box.createHorizontalStrut(30));

		btnGo = new JButton("Go");
		topBox.add(btnGo);
		btnGo.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				browse();
			}
		});

		paneInhalt = new JScrollPane();
		paneInhalt.setPreferredSize(new java.awt.Dimension(600, 300));
		txtInhalt = new JTextArea();
		txtInhalt.setFont(new java.awt.Font("Courier New", 0, 12));
		paneInhalt.setViewportView(txtInhalt);
		this.add(paneInhalt, BorderLayout.CENTER);

		pack();
		setVisible(true);
	}

	private void browse() {
		Socket s = null;
		OutputStreamWriter out = null;
		BufferedReader inReader = null;
		String lineIn;
		StringBuffer urlInhalt = new StringBuffer();

		// Network errors are always possible
		try {
			// Set up the socket
			s = new Socket(txtIP.getText(), new Integer(txtPort.getText()));

			// Send our request, using the HTTP 1.0 protocol
			out = new OutputStreamWriter(s.getOutputStream());
			out.write("GET / HTTP/1.0\n");
			out.write("User-Agent: Browser0\n");
			out.write("Host: " + txtIP.getText() + ":" + txtPort.getText() + "\n");
			out.write("Accept: text/html, */*\n\n");
			out.flush();

			// Set up the reader classes
			InputStream in1 = s.getInputStream();
			InputStreamReader in2 = new InputStreamReader(in1);
			inReader = new BufferedReader(in2);

			while ((lineIn = inReader.readLine()) != null) {
				urlInhalt.append(lineIn + "\n");
			}

			// Show the result in "txtInhalt"
			txtInhalt.setText(urlInhalt.toString());
		}

		// If an error occurred, show the error message in txtInhalt
		catch (Exception err) {
			txtInhalt.setText("ERROR: " + err.toString());
		} finally {
			try {
				if (out != null) out.close();
				if (inReader != null) inReader.close();
				if (s != null) s.close();
			} catch (Exception e) {
			}
		}
	}
}
